import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import java.util.Set;

/**
 * 
 * @author "Cunxin Jia"
 *
 */
public class Clause {
	private Literal head;
	private Set<Literal> body;
	
	public Clause(Literal head, Set<Literal> body) {
		this.head = head;
		this.body = body;
	}
	
	public Clause(String clauseString) {
		int bodyIndex = clauseString.indexOf(":-");
		String headString = clauseString.substring(0, bodyIndex).trim();
		String bodyString = clauseString.substring(bodyIndex + 2).trim();
		head = new Literal(headString);
		Scanner input = new Scanner (bodyString);
		input.useDelimiter("\\),");
		body = new HashSet<Literal>();
		while(input.hasNext()) {			
			String curLiteral = input.next().trim();
			if(curLiteral.charAt(curLiteral.length() - 1) == '.') {
				curLiteral = curLiteral.substring(0,curLiteral.length() - 1);
				body.add(new Literal(curLiteral));
				break;
			}
			curLiteral += ")";
			body.add(new Literal(curLiteral));
		}
	}
	
	public Literal getHead() {
		return head;
	}
	
	public Set<Literal> getBody() {
		return body;
	}
	
	public String toString() {
		String clauseString = head.toString() + " :- ";
		Iterator<Literal> iter = body.iterator();
		while(iter.hasNext()) {
			Literal curLiteral = iter.next();			
			clauseString += curLiteral.toString() + ", ";
		}
		clauseString = clauseString.substring(0, clauseString.length() - 2) + ".";
		return clauseString;
	}
}
